package com.study.experiment06;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.ServletActionContext;

import javax.servlet.ServletContext;

public class Login2 extends ActionSupport implements ModelDriven<User> {
    private User user = new User();

    public String login() {
        if (user.getUsername().equals("admin") && user.getPassword().equals("admin")) {
            int onlineUserCount = 0;
            ServletContext servletContext = ServletActionContext.
                    getServletContext();
            synchronized (servletContext) {
                try {
                    Object obj = servletContext.getAttribute("onlineUserCount");
                    onlineUserCount = (Integer) (obj != null ? obj : 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                servletContext.setAttribute("onlineUserCount",
                        onlineUserCount + 1);
            }
            return "success";
        } else {
            return "input";
        }

    }

    public String logout() {
        int onlineUserCount = 0;
        ServletContext servletContext = ServletActionContext.
                getServletContext();
        synchronized (servletContext) {
            try {
                onlineUserCount = (Integer) servletContext
                        .getAttribute("onlineUserCount");
            } catch (Exception e) {
            }
            servletContext.setAttribute("onlineUserCount",
                    onlineUserCount - 1);
        }
        return "success";
    }

    @Override
    public User getModel() {
        return user;
    }
}

